package com.itheima.aop;

import com.itheima.mapper.EmpLoginLogMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpLoginLog;
import com.itheima.pojo.LogInFo;
import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@Slf4j
@Aspect
public class OpeateLoginLogAspect {
    @Autowired
    private EmpLoginLogMapper empLoginLogMapper;

    //切入点表达式
    @Pointcut("execution(* com.itheima.controller.LoginController.Login(com.itheima.pojo.Emp))")
    public void pt() {
    }

    //环绕型通知
    @Around("pt()")
    public Object recordOperateLoginLog(ProceedingJoinPoint joinPoint) throws Throwable {
        // 记录开始时间
        long begin = System.currentTimeMillis();
        //  调用原始方法
        Object result = joinPoint.proceed();
        // 记录结束时间和耗时
        long end = System.currentTimeMillis();
        long costTime = end - begin;

        //  创建登录日志对象
        EmpLoginLog empLoginLog = new EmpLoginLog();
        //设置对象属性
        /*
         * 1. 获取用户名和密码(无论是否正确都要获取）
         */
        Object[] args = joinPoint.getArgs();
        String loginInfo = getLoginInFo(args);
        String username = loginInfo.split(",")[0];
        String password = loginInfo.split(",")[1];

        empLoginLog.setUsername(username);//1 设置对象用户名
        empLoginLog.setPassword(password);//2 设置对象密码

        /*
         * 3. 设置登录时间，耗时，JWT令牌()
         * 成功登录和失败登录(成功获取登录令牌，失败令牌设置为空) 设置登录时间，耗时，JWT令牌
         */
        empLoginLog.setLoginTime(LocalDateTime.now());
        empLoginLog.setCostTime(costTime);

        if (result instanceof Result) {
            Result apiResult = (Result) result;
            Integer code = apiResult.getCode();

            if (code != null && code == 1) {
                empLoginLog.setIsSuccess((short) 1);//设置成功登录
                // 从返回值中获取 JWT 令牌
                Object data = apiResult.getData();
                if (data instanceof LogInFo) {
                    LogInFo logInFo = (LogInFo) data;
                    String jwt = logInFo.getToken();
                    empLoginLog.setJwt(jwt);
                    log.info("登录成功，获取到 JWT 令牌");
                } else {
                    log.warn("登录成功，但返回数据类型不是 LogInFo，无法获取 JWT");
                    empLoginLog.setJwt("");
                }
            } else {
                empLoginLog.setIsSuccess((short) 0);
                empLoginLog.setJwt(""); // 登录失败，JWT 置空
                String errorMsg = apiResult.getMsg() != null ? apiResult.getMsg() : "登录失败";
                log.info("登录失败，错误信息: {}", errorMsg);
            }
        } else {
            empLoginLog.setIsSuccess((short) 0);
            empLoginLog.setJwt("");
            log.warn("返回值不是 Result 类型");
        }

        log.info("保存登录日志: {}", empLoginLog);
        empLoginLogMapper.insert(empLoginLog);
        return result;
    }

    public String getLoginInFo(Object[] args) {
        String username = "";
        String password = "";
        for (Object arg : args) {
            if (arg instanceof Emp) {
                Emp emp = (Emp) arg;
                username = emp.getUsername() != null ? emp.getUsername() : "";
                password = emp.getPassword() != null ? emp.getPassword() : "";
                break;
            }
        }
        return username + "," + password;
    }
}